import NavBar from "@/components/NavBar"
import Input from "@/components/Input"
import styles from './index.module.scss'
import { useFormik } from "formik"
import { sendValidationCode, login } from "@/store/actions/login"
import { useDispatch } from "react-redux"
import { Toast } from 'antd-mobile'
import { useState } from "react"
import {useNavigate, useLocation} from 'react-router-dom'
export default function Login() {
    const [time, setTime] = useState(0)
    const navigate = useNavigate()
    const location = useLocation()
    const dispatch = useDispatch()
    // 发送验证码
    const onSendSms = async () => {
        // 发送完验证码后使下面代码60秒内不执行
        if(time>0) return 
        const mobile = form.values.mobile
        // 先对手机号进行验证
        if(!/^1[3-9]\d{9}$/.test(mobile)){
            // 让隐藏的错误信息做一个显示
            form.setTouched({
                mobile:true,
            })
            return 
        }
        try {
            // 获取 Action
            const action =  sendValidationCode(mobile)
            // console.log(action,'action')
            // 调用 Action
            await dispatch(action)
            Toast.show('获取验证码成功')

            // 开启倒计时
            setTime(60)
            // console.log(time)
            let timeId = setInterval(()=>{
                // 每次都想要获取最新的状态 所以要写成箭头函数
                setTime(time=>{
                    if(time === 1){
                        clearInterval(timeId)
                    }
                    return time - 1
                })
            },1000)
        } catch (err) {
            // console.log(err)
            if(err.response){
                Toast.show(err.response.data.message)
            }else{
                Toast.show('服务器繁忙请稍后')
            }
        }
    }
    // Formik 表单对象
    const form = useFormik({
        // 设置表单字段的初始值
        initialValues: {
            mobile: '13900001111',
            code: '246810',
        },
        // 提交 表单数据
        onSubmit: async (values) => {
            // console.log(values, 'values')
            // 发送登录的请求接口
           await dispatch(login(values))
        //    console.log(location,'location')
        const {state} = location
        if(!state){
            navigate('/') 
        }else{
            // 回退到上一页
            // navigate(state.form)
        }
        },
        // 验证 自定义校验
        validate(values) {
            const errors = {}
            if (!values.mobile) {
                errors.mobile = '手机号不能为空'
            }
            if (!values.code) {
                errors.code = '验证码不能为空'
            }
            return errors
        }
    })
    const { errors, handleSubmit,handleBlur, values, handleChange,touched } = form
    return (
        <div className={styles.root}>
            {/* 顶部导航 */}
            <NavBar>
                标题
            </NavBar>
            {/* 登录表单 */}
            <div className="content">
                <h3>短信登录</h3>
                <form onSubmit={handleSubmit}>
                    <div className="input-item">
                        <div className="input-box">
                            <Input
                                name='mobile'
                                placeholder='请输入手机号'
                                value={values.mobile}
                                onChange={handleChange}></Input>
                        </div>
                        {touched.mobile && errors.mobile ? (
                            <div className="validate">手机号验证错误</div>
                        ) : null}
                    </div>
                    <div className="input-item">
                        <div className="input-box">
                            <Input
                                name='code'
                                placeholder='请输入验证码'
                                value={values.code}
                                maxLength={6}
                                extra={time===0 ? '发送验证码': time + 's后发送'}
                                onChange={handleChange}
                                onExtraClick={onSendSms}
                                onBlur={handleBlur}></Input>
                        </div>
                        {errors.code ? (
                            <div className="validate">验证码错误</div>
                        ) : null}
                    </div>
                    {/* 登录按钮 */}
                    <button type="submit" className="login-btn">
                        登录
                    </button>
                </form>
            </div>
        </div>)
}